<template>
  <div class="opportunity-list">
    <div class="header">
      <h2>销售机会</h2>
      <div class="header-actions">
        <el-button type="primary" @click="handleAdd">新增机会</el-button>
      </div>
    </div>

    <div class="filter">
      <el-form :model="searchForm" inline>
        <el-form-item label="客户名称">
          <el-input
            v-model="searchForm.customerName"
            placeholder="请输入客户名称"
            clearable
            style="width: 200px"
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="线索类别">
          <el-select
            v-model="searchForm.category"
            placeholder="请选择"
            clearable
            style="width: 150px"
          >
            <el-option label="案件委托" :value="1" />
            <el-option label="法务需求" :value="2" />
            <el-option label="法务专项" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="线索等级">
          <el-select v-model="searchForm.level" placeholder="请选择" clearable style="width: 150px">
            <el-option label="A级-本月内可签约" :value="1" />
            <el-option label="B级-30天内可签约" :value="2" />
            <el-option label="C级-持续跟进" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择"
            clearable
            style="width: 120px"
          >
            <el-option label="有效" :value="1" />
            <el-option label="已转化" :value="2" />
            <el-option label="已失效" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <el-table
      :data="tableData"
      v-loading="loading"
      stripe
      style="width: 100%"
    >
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="customer_name" label="客户名称" min-width="150" />
      <el-table-column prop="customer_type" label="客户类型" width="100">
        <template #default="scope">
          <el-tag v-if="scope.row.customer_type === 1" type="info">个人</el-tag>
          <el-tag v-else type="success">企业</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="category" label="线索类别" width="120">
        <template #default="scope">
          <el-tag v-if="scope.row.category === 1" type="danger">案件委托</el-tag>
          <el-tag v-else-if="scope.row.category === 2" type="warning">法务需求</el-tag>
          <el-tag v-else type="primary">法务专项</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="level" label="线索等级" width="150">
        <template #default="scope">
          <el-tag v-if="scope.row.level === 1" type="danger">A级-本月内可签约</el-tag>
          <el-tag v-else-if="scope.row.level === 2" type="warning">B级-30天内可签约</el-tag>
          <el-tag v-else type="info">C级-持续跟进</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag v-if="Number(scope.row.status) === 1" type="success">有效</el-tag>
          <el-tag v-else-if="Number(scope.row.status) === 2" type="info">已转化</el-tag>
          <el-tag v-else type="danger">已失效</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="user_name" label="负责人" width="120" />
      <el-table-column prop="discovery_date" label="发现日期" width="120">
        <template #default="scope">
          {{ formatDate(scope.row.discovery_date) }}
        </template>
      </el-table-column>
      <el-table-column prop="create_time" label="创建时间" width="160">
        <template #default="scope">
          {{ formatDateTime(scope.row.create_time) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" align="center" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="handleDetail(row)">查看</el-button>
          <el-dropdown size="small">
            <el-button type="default" size="small">
              更多
              <el-icon class="el-icon--right">
                <ArrowDown />
              </el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="handleEdit(row)">编辑</el-dropdown-item>
                <el-dropdown-item
                  v-if="Number(row.status) === 1"
                  @click="handleConvert(row)"
                >
                  转化为订单
                </el-dropdown-item>
                <el-dropdown-item divided @click="handleDelete(row)" style="color: #f56c6c">
                  删除
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.limit"
        :page-sizes="[20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 销售机会表单抽屉 -->
    <OpportunityForm
      v-model="opportunityFormVisible"
      :opportunity-id="currentOpportunityId"
      :mode="formMode"
      @success="handleOpportunityFormSuccess"
    />
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { ArrowDown } from '@element-plus/icons-vue'
  import {
    opportunityApi,
    Opportunity,
    OpportunitySearchParams,
  } from '@/api/crm/opportunity'
  import OpportunityForm from '@/views/crm/components/OpportunityForm.vue'

  // 搜索表单
  const searchForm = reactive({
    customerName: '',
    category: '',
    level: '',
    status: '',
  })

  // 表格数据
  const tableData = ref<any[]>([])
  const loading = ref(false)
  const pagination = reactive({
    page: 1,
    limit: 20,
    total: 0,
  })

  // 抽屉
  const opportunityFormVisible = ref(false)
  const currentOpportunityId = ref(0)
  const formMode = ref('add')

  // 初始化
  onMounted(() => {
    fetchData()
  })

  // 获取表格数据
  const fetchData = async () => {
    loading.value = true
    try {
      const params: OpportunitySearchParams = {
        page: pagination.page,
        limit: pagination.limit,
        customerName: searchForm.customerName || undefined,
        category: searchForm.category ? Number(searchForm.category) : undefined,
        level: searchForm.level ? Number(searchForm.level) : undefined,
        status: searchForm.status ? Number(searchForm.status) : undefined,
      }
      const response = await opportunityApi.getOpportunityList(params)
      tableData.value = response.data.list || []
      pagination.total = response.data.total || 0
    } catch (error) {
      console.error(error)
      ElMessage.error('获取数据失败')
    } finally {
      loading.value = false
    }
  }

  // 搜索
  const handleSearch = () => {
    pagination.page = 1
    fetchData()
  }

  // 重置
  const handleReset = () => {
    searchForm.customerName = ''
    searchForm.category = ''
    searchForm.level = ''
    searchForm.status = ''
    handleSearch()
  }

  // 新增
  const handleAdd = () => {
    currentOpportunityId.value = 0
    formMode.value = 'add'
    opportunityFormVisible.value = true
  }

  // 查看详情
  const handleDetail = (row: any) => {
    currentOpportunityId.value = row.id
    formMode.value = 'view'
    opportunityFormVisible.value = true
  }

  // 编辑
  const handleEdit = (row: any) => {
    currentOpportunityId.value = row.id
    formMode.value = 'edit'
    opportunityFormVisible.value = true
  }

  // 转化为订单
  const handleConvert = async (row: any) => {
    try {
      await ElMessageBox.confirm('确定要将此线索转化为订单吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      await opportunityApi.convertOpportunity({ id: row.id })
      ElMessage.success('转化成功，请前往订单模块创建订单')
      fetchData()
    } catch (error) {
      console.log('用户取消')
    }
  }

  // 删除
  const handleDelete = async (row: any) => {
    try {
      await ElMessageBox.confirm('确定要删除此线索吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      await opportunityApi.deleteOpportunity({ id: row.id })
      ElMessage.success('删除成功')
      fetchData()
    } catch (error) {
      console.log('用户取消')
    }
  }

  // 销售机会表单提交成功
  const handleOpportunityFormSuccess = () => {
    opportunityFormVisible.value = false
    currentOpportunityId.value = 0
    formMode.value = 'add'
    fetchData()
  }

  // 分页
  const handleSizeChange = (val: number) => {
    pagination.limit = val
    fetchData()
  }

  const handleCurrentChange = (val: number) => {
    pagination.page = val
    fetchData()
  }

  // 格式化日期
  const formatDate = (timestamp: number | string) => {
    if (!timestamp) return ''
    const date = new Date(
      typeof timestamp === 'string' ? parseInt(timestamp) * 1000 : timestamp * 1000
    )
    return date.toLocaleDateString()
  }

  const formatDateTime = (timestamp: number | string) => {
    if (!timestamp) return ''
    const date = new Date(
      typeof timestamp === 'string' ? parseInt(timestamp) * 1000 : timestamp * 1000
    )
    return date.toLocaleString()
  }
</script>

<style scoped>
  .opportunity-list {
    padding: 20px;
  }

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
  }

  .header-actions {
    display: flex;
    gap: 10px;
  }

  .filter {
    background: #f5f7fa;
    padding: 20px;
    margin-bottom: 20px;
    border-radius: 4px;
  }

  .pagination {
    margin-top: 20px;
    text-align: right;
  }
</style>
